
const path = require('path');
const fs = require('fs');
const CJCONFIG = global.CJCONFIG;
const mongoose = require('mongoose');
const conn = mongoose.createConnection(CJCONFIG.mongodb.mongo.uri);
const Logger = global.Logger('sql');

conn.on('error', function () {
    Logger.error('Mongo Connection Error. Make sure server is running', CJCONFIG.mongodb.mongo.uri);
    throw new Error('mongoStatusError');
});
conn.once('open', function() {
    Logger.info('open mongodb success', CJCONFIG.mongodb.mongo.uri);
});

mongoose.set('debug', true);

mongoose.set('debug', function (collectionName, method, query, doc, options) {
    //print sql
    Logger.info(
        'db.' +
        collectionName +
        '.' +
        method +
        '(' +
        JSON.stringify(query) +
        ', ' +
        JSON.stringify(doc.fields)  +
        ', ' +
        JSON.stringify(doc.options) +
        ')');
});

let db = {};

fs
    .readdirSync(__dirname)
    .filter(function (file) {
        return (/\.\w+?$/.exec(file)[0] === '.js') && (file !== 'index.js');
    })
    .forEach(function (file) {
        let model = require((path.join(__dirname, file)))(conn, mongoose.Schema);
        db[model.modelName] = model;
    });

module.exports = db;